package com.ruoyi.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.his.domain.*;
import com.ruoyi.his.domain.vo.HisDataVo;
import com.ruoyi.his.domain.vo.HisHosTypeVo;
import com.ruoyi.his.domain.vo.HisLogVo;
import com.ruoyi.his.domain.vo.QueryAnalysisDo;
import com.ruoyi.his.mapper.*;
import com.ruoyi.his.service.IHisLargeScreenService;
import com.ruoyi.system.domain.HisEngineRuleGroup;
import com.ruoyi.system.domain.HisHospitalNation;
import com.ruoyi.system.domain.vo.HisHospitalNationVo;
import com.ruoyi.system.mapper.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 *
 *
 * @author Alan
 * @date 2024-03-09
 */
@Service
public class HisLargeScreenServiceImpl implements IHisLargeScreenService {

    @Autowired
    private AppAnalysisResultMapper appAnalysisResultMapper;

    @Autowired
    private AppAnalysisResultTmpMapper appAnalysisResultTmpMapper;
    @Autowired
    private WarnPreLogMapper warnPreLogMapper;
    @Autowired
    private WarnHospitalLogMapper warnHospitalLogMapper;
    @Autowired
    private HisHospitalNationMapper hisHospitalNationMapper;

    @Autowired
    private HisPunishMapper hisPunishMapper;


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private HisEngineWarnTypeMapper engineWarnTypeMapper;

    @Autowired
    private OdsHospitalDataMapper odsHospitalDataMapper;

    @Autowired
    private HisDepartmentMapper hisDepartmentMapper;

    @Autowired
    private HisEngineRuleGroupMapper hisEngineRuleGroupMapper;

    @Autowired
    private OdsHospitalAllMapper odsHospitalAllMapper;

    @Autowired
    private ReProvinceMapper reProvinceMapper;

    @Autowired
    private ReAreaMapper reAreaMapper;

    @Autowired
    private ReCityMapper reCityMapper;

    @Autowired
    private ReStreetMapper reStreetMapper;

    @Autowired
    private HisAreaMapper hisAreaMapper;

    @Override
    public Map getAnalysisResult(List<String> hospitalIds, List<String> signatures) {
        Map map =new HashMap();

        AppAnalysisResultTmp todayclinic= todayclinic(hospitalIds,signatures);


        AppAnalysisResultTmp pre= pre(hospitalIds,signatures);



        AppAnalysisResult clinicRes= clinicRes(hospitalIds,signatures);

        AppAnalysisResult preRes= preRes(hospitalIds,signatures);
        long tclinic = 0;
        long tpre = 0;
        long allclinic = 0;
        long allpre = 0;
        if(todayclinic!=null){
            tclinic = todayclinic.getValue();
        }
        if(pre!=null){
            tpre = pre.getValue();
        }
        if(clinicRes!=null){
            allclinic = clinicRes.getValue();
        }
        if(preRes!=null){
            allpre = preRes.getValue();
        }
        map.put("todayJiuZhen",tclinic);
        map.put("todayChuFang",tpre);
        map.put("totalJiuZhen",allclinic + tclinic);  //需要加上今天的数据
        map.put("totalChuFang",allpre + tpre); //同上
        return map;
    }

    private AppAnalysisResult preRes(List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResult> queryWrappers = new QueryWrapper<AppAnalysisResult>();
        queryWrappers.select("sum(value) as value");
        queryWrappers.eq("type","pre");
        queryWrappers.in("hospital_id",hospitalIds);
        queryWrappers.in("signature",signatures);
        AppAnalysisResult preRes = appAnalysisResultMapper.selectOne(queryWrappers);
        return preRes;
    }

    private AppAnalysisResult clinicRes(List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResult> queryWrapper = new QueryWrapper<AppAnalysisResult>();
        queryWrapper.select("sum(value) as value");
        queryWrapper.eq("type","clinic");
        queryWrapper.in("hospital_id",hospitalIds);
        queryWrapper.in("signature",signatures);
        AppAnalysisResult clinicRes= appAnalysisResultMapper.selectOne(queryWrapper);
        return clinicRes;
    }

    private AppAnalysisResultTmp pre(List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResultTmp> queryWrapperPre = new QueryWrapper<AppAnalysisResultTmp>();
        queryWrapperPre.select("sum(value) as value");
        queryWrapperPre.eq("type","pre");
        queryWrapperPre.in("hospital_id",hospitalIds);
        queryWrapperPre.in("signature",signatures);
        queryWrapperPre.last("limit 1");
        AppAnalysisResultTmp pre= appAnalysisResultTmpMapper.selectOne(queryWrapperPre);
        return pre;
    }

    private AppAnalysisResultTmp todayclinic(List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResultTmp> queryWrapperClinic = new QueryWrapper<AppAnalysisResultTmp>();
        queryWrapperClinic.select("sum(value) as value");
        queryWrapperClinic.eq("type","clinic");
        queryWrapperClinic.in("hospital_id",hospitalIds);
        queryWrapperClinic.in("signature",signatures);
        queryWrapperClinic.last("limit 1");
        AppAnalysisResultTmp clinic=  appAnalysisResultTmpMapper.selectOne(queryWrapperClinic);
        return clinic;
    }

    private AppAnalysisResultTmp preWhithRegister(String signature,String hospitalId, List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResultTmp> queryWrapperPre = new QueryWrapper<AppAnalysisResultTmp>();
        queryWrapperPre.select("sum(value) as value");
        queryWrapperPre.eq("type","pre");
        queryWrapperPre.eq("signature",signature);
        queryWrapperPre.eq("hospital_id",hospitalId);
        queryWrapperPre.in("hospital_id",hospitalIds);
        queryWrapperPre.in("signature",signatures);
        queryWrapperPre.last("limit 1");
        AppAnalysisResultTmp pre= appAnalysisResultTmpMapper.selectOne(queryWrapperPre);
        return pre;
    }

    private AppAnalysisResultTmp clinicWhithRegister(String signature,String hospitalId,  List<String> hospitalIds, List<String> signatures) {
        QueryWrapper<AppAnalysisResultTmp> queryWrapperClinic = new QueryWrapper<AppAnalysisResultTmp>();
        queryWrapperClinic.select("sum(value) as value");
        queryWrapperClinic.eq("type","clinic");
        queryWrapperClinic.eq("signature",signature);
        queryWrapperClinic.eq("hospital_id",hospitalId);
        queryWrapperClinic.in("hospital_id",hospitalIds);
        queryWrapperClinic.in("signature",signatures);
        queryWrapperClinic.last("limit 1");
        AppAnalysisResultTmp clinic=  appAnalysisResultTmpMapper.selectOne(queryWrapperClinic);
        return clinic;
    }


    @Override
    public Map warnList(List<String> hospitalIds, List<String> signatures) {
        Set<String> todayHosSet = new HashSet<>();
        Set<String> hosSet = new HashSet<>();
        //今日医院预警
        List<WarnHospitalLog> todayhos = warnHospitalLogMapper.selectList(new LambdaQueryWrapper<WarnHospitalLog>().isNotNull(WarnHospitalLog::getHospitalId).isNotNull(WarnHospitalLog::getSignature)
                .apply("DATE(warn_time) = DATE({0})", LocalDate.now())
                .in(WarnHospitalLog::getHospitalId, hospitalIds)
                .in(WarnHospitalLog::getSignature, signatures)
        );
        for(WarnHospitalLog item :todayhos){
            String p = item.getHospitalId();
            String s = item.getSignature();
            String va = p+s;
            todayHosSet.add(va);
        }


        //所有医院预警
        List<WarnHospitalLog> allhos = warnHospitalLogMapper.selectList(new LambdaQueryWrapper<WarnHospitalLog>().isNotNull(WarnHospitalLog::getHospitalId).isNotNull(WarnHospitalLog::getSignature)
                .in(WarnHospitalLog::getHospitalId, hospitalIds)
                .in(WarnHospitalLog::getSignature, signatures)
        );
        for(WarnHospitalLog item :allhos){
            String p = item.getHospitalId();
            String s = item.getSignature();
            String va = p+s;
            hosSet.add(va);
        }

        //今日处方预警
        List<WarnPreLog> todayPre = warnPreLogMapper.selectList(new LambdaQueryWrapper<WarnPreLog>().isNotNull(WarnPreLog::getHospitalId).isNotNull(WarnPreLog::getSignature)
                .apply("DATE(warn_time) = DATE({0})", LocalDate.now())
                .in(WarnPreLog::getHospitalId, hospitalIds)
                .in(WarnPreLog::getSignature, signatures)
        );
        for(WarnPreLog item :todayPre){
            String p = item.getHospitalId();
            String s = item.getSignature();
            String va = p+s;
            todayHosSet.add(va);
        }

        //所有处方预警
        List<WarnPreLog> allPre = warnPreLogMapper.selectList(new LambdaQueryWrapper<WarnPreLog>().isNotNull(WarnPreLog::getHospitalId).isNotNull(WarnPreLog::getSignature)
                .in(WarnPreLog::getHospitalId, hospitalIds)
                .in(WarnPreLog::getSignature, signatures));
        for(WarnPreLog item :allPre){
            String p = item.getHospitalId();
            String s = item.getSignature();
            String va = p+s;
            hosSet.add(va);
        }
//        int totalWarningOrg = warnPreLogMapper.selectWarnAllCount();
        int totalWarningOrg = hosSet.size();
        //今日医院处置数
        Set<String> todayPset = new HashSet<>();
        Set<String> totalPset = new HashSet<>();
        List<HisPunish>  todayP =  hisPunishMapper.selectList(new LambdaQueryWrapper<HisPunish>().isNotNull(HisPunish::getHospitalId).isNotNull(HisPunish::getSignature)
                .apply("DATE(punish_time) = DATE({0})", LocalDate.now())
                .in(HisPunish::getHospitalId, hospitalIds)
                .in(HisPunish::getSignature, signatures)
        );
        for(HisPunish punish : todayP){
            String p = punish.getHospitalId();
            String s = punish.getSignature();
            String va = p+s;
            todayPset.add(va);
        }
        //所有医院处置数
        List<HisPunish>  allP =  hisPunishMapper.selectList(new LambdaQueryWrapper<HisPunish>().isNotNull(HisPunish::getHospitalId).isNotNull(HisPunish::getSignature)
                .in(HisPunish::getHospitalId, hospitalIds)
                .in(HisPunish::getSignature, signatures));
        for(HisPunish punish : allP){
            String p = punish.getHospitalId();
            String s = punish.getSignature();
            String va = p+s;
            totalPset.add(va);
        }
        Map map =new HashMap();
        map.put("totalWarningOrg",totalWarningOrg);
        map.put("todayWarningOrg",todayHosSet.size());
        map.put("todayHandled",todayP.size());
        map.put("totalHandled",allP.size());
        return map;
    }

    @Override
    public  List<QueryAnalysisDo> hospitalOdsList(List<String> hospitalIds, List<String> signatures){
        List<QueryAnalysisDo> mapList=new ArrayList<>();
        OdsHospitalAll param0 = new OdsHospitalAll();
        param0.setIntonum(1);
        param0.setHospitalIds(hospitalIds);
        param0.setSignatures(signatures);
        List<OdsHospitalAll>  list = odsHospitalAllMapper.selectOdsHospitalAllList(param0);
        QueryAnalysisDo param = new QueryAnalysisDo();
        HisDepartment deptparam = new HisDepartment();
        for (OdsHospitalAll hos:list){
            //监控数
            Long monitorCount = 0L;
            //医院名称
            String name;
            //总处方
            Long totalPrescription = 0L;
            //今日处方
            Long todayPrescription  = 0L;
            //总就诊
            Long totalOutpatient  = 0L;
            //今日就诊
            Long todayOutpatient  = 0L;
            //总预警数
            Long totalWarning  = 0L;
            //今日预警数
            Long todayWarning  = 0L;

            //今日就诊数
            QueryAnalysisDo hitem = new QueryAnalysisDo();
            param.setIsnow(true);
            param.setType("clinic");
            AppAnalysisResultTmp t_tmp = preWhithRegister(hos.getSignature(),hos.getHospitalId(),hospitalIds,signatures);
            if(t_tmp!=null){
                todayOutpatient = Long.valueOf(t_tmp.getValue());
            }
            //今日处方数
            param.setType("pre");
            AppAnalysisResultTmp t_ptmp = clinicWhithRegister(hos.getSignature(),hos.getHospitalId(),hospitalIds,signatures);
            if(t_ptmp!=null){
                todayPrescription = Long.valueOf(t_ptmp.getValue());
            }
            param.setHospitalIds(hospitalIds);
            param.setSignatures(signatures);

            //总就诊数
            param.setIsnow(false);
            param.setType("clinic");
            param.setIsnow(false);
            param.setHospitalId(hos.getHospitalId());
            param.setSignature(hos.getSignature());
            totalOutpatient =  hisHospitalNationMapper.selectAnalysisResult(param);
            if(totalOutpatient==null){
                totalOutpatient = 0L;
            }
            //总处方数
            param.setType("pre");
            param.setIsnow(false);
            totalPrescription =  hisHospitalNationMapper.selectAnalysisResult(param);
            if(totalPrescription==null){
                totalPrescription = 0L;
            }
            hitem.setName(hos.getInstitutionName());
            hitem.setTodayOutpatient(todayOutpatient);
            hitem.setTodayPrescription(todayPrescription);
            hitem.setTotalOutpatient(totalOutpatient);
            hitem.setTotalPrescription(totalPrescription);
            //今日预警数
            Integer allwarn1 = warnHospitalLogMapper.selectCount(new LambdaQueryWrapper<WarnHospitalLog>()
                    .eq(WarnHospitalLog::getHospitalId,hos.getHospitalId())
                    .eq(WarnHospitalLog::getSignature,hos.getSignature())
                    .in(WarnHospitalLog::getHospitalId,hospitalIds)
                    .in(WarnHospitalLog::getSignature,signatures)
            );
            Integer twarn1 = warnHospitalLogMapper.selectCount(new LambdaQueryWrapper<WarnHospitalLog>()
                    .apply("DATE(warn_time) = DATE({0})", LocalDate.now())
                    .eq(WarnHospitalLog::getHospitalId,hos.getHospitalId())
                    .eq(WarnHospitalLog::getSignature,hos.getSignature())
                    .in(WarnHospitalLog::getHospitalId,hospitalIds)
                    .in(WarnHospitalLog::getSignature,signatures)
            );
            Integer allPre = warnPreLogMapper.selectCount(new LambdaQueryWrapper<WarnPreLog>()
                    .eq(WarnPreLog::getHospitalId,hos.getHospitalId())
                    .eq(WarnPreLog::getSignature,hos.getSignature())
                    .in(WarnPreLog::getHospitalId,hospitalIds)
                    .in(WarnPreLog::getSignature,signatures)
            );
            Integer tPre = warnPreLogMapper.selectCount(new LambdaQueryWrapper<WarnPreLog>()
                    .apply("DATE(warn_time) = DATE({0})", LocalDate.now())
                    .eq(WarnPreLog::getHospitalId,hos.getHospitalId())
                    .eq(WarnPreLog::getSignature,hos.getSignature())
                    .in(WarnPreLog::getHospitalId,hospitalIds)
                    .in(WarnPreLog::getSignature,signatures)
            );
            deptparam.setHospitalIds(hospitalIds);
            deptparam.setSignatures(signatures);
            deptparam.setHospitalId(hos.getHospitalId());
            deptparam.setSignature(hos.getSignature());
            List<HisDepartment> ldept = hisDepartmentMapper.selectHisDepartmentList(deptparam);
            hitem.setMonitorCount(0);
            if(StringUtils.isNotEmpty(ldept)){
                HisDepartment dept = ldept.get(0);
                String divs = dept.getDeviceId();
                List l= StringUtils.str2List(divs,",",true,true);
                hitem.setMonitorCount(l.size());
            }
            hitem.setTodayWarning(Long.valueOf(twarn1+tPre));
            hitem.setTotalWarning(Long.valueOf(allwarn1+allPre));
            mapList.add(hitem);
        }
        return mapList;
    }
   /* @Override
    public List<Map> hospitalNationList() {
        List<Map> mapList=new ArrayList<>();
        List<HisHospitalNationVo> hisHospitalNationVos = hisHospitalNationMapper.selectHisHospitalNationLists(new HisHospitalNation());
        for (HisHospitalNationVo hisHospitalNationVo:hisHospitalNationVos){
            long tclinic = 0;
            long tpre = 0;
            long allclinic = 0;
            long allpre = 0;
            if(preRes(hospitalIds, signatures)!=null){
                allpre = preRes(hospitalIds, signatures).getValue();
            }
            if(todayclinic(hospitalIds, signatures)!=null){
                tclinic = todayclinic(hospitalIds, signatures).getValue();
            }
            if(pre(hospitalIds, signatures)!=null){
                tpre = pre(hospitalIds, signatures).getValue();
            }
            if(clinicRes(hospitalIds, signatures)!=null){
                allclinic = clinicRes(hospitalIds, signatures).getValue();
            }
            Map map =new HashMap();
            map.put("name",hisHospitalNationVo.getName());
            //总处方
            map.put("totalPrescription",allpre);

            //今日就诊数

            map.put("todayOutpatient",tclinic);
            //今日处方数
            map.put("todayPrescription",tpre);

            //总就诊数
            map.put("totalOutpatient",allclinic);

            Integer count = warnHospitalLogMapper.selectCount(new LambdaQueryWrapper<WarnHospitalLog>());
            Integer counts = warnHospitalLogMapper.selectCount(new LambdaQueryWrapper<WarnHospitalLog>()
                    .eq(WarnHospitalLog::getWarnTime,DateUtils.dateTime(new Date())));
            Integer countPre = warnPreLogMapper.selectCount(new LambdaQueryWrapper<WarnPreLog>());
            Integer countsPre = warnPreLogMapper.selectCount(new LambdaQueryWrapper<WarnPreLog>()
                    .eq(WarnPreLog::getPreTime,DateUtils.dateTime(new Date())));
            //总预警数
            map.put("totalWarning",count+countPre);
            //今日预警数
            map.put("todayWarning",counts+countsPre);
            mapList.add(map);
        }

        return mapList;
    }*/


    @Override
    public List<Map> toDayWarn(List<String> hospitalIds, List<String> signatures) {
        List<Map> mapList1 = warnPreLogMapper.toDayWarnHos(hospitalIds,signatures);
        List<Map> mapList2 = warnPreLogMapper.toDayWarnPre(hospitalIds,signatures);
        mapList1 = make(mapList1,0);
        mapList2 = make(mapList2,1);
        List<Map> collect = new ArrayList<>();
        collect.addAll(mapList1);
        collect.addAll(mapList2);
        //去重
        Map<String,Map> tmp = new HashMap<>();
        for(Map map : collect){
            if (map.get("register_number")!=null&&map.get("register_number")!="") {
                tmp.put(map.get("register_number").toString(),map);
            }
        }
        List<Map> result = new ArrayList<>();
        for(String key: tmp.keySet()){
            Map m = tmp.get(key);
            result.add(m);
        }
        return result;
    }
    public List<Map> make(List<Map> mapList,int type ){
        for (Map map:mapList){
            Map cmap  = null;
            if(type==1){
                cmap = warnPreLogMapper.toDayWarnPreInfo(map.get("hospital_id").toString(),map.get("signature").toString());
            }else if(type==0){
                cmap = warnPreLogMapper.toDayWarnHosInfo(map.get("hospital_id").toString(),map.get("signature").toString());
            }
            map.put("monitor",0);
            map.put("handle_state",0);
            map.put("handlePerson","");
            map.put("warningName","");
            map.put("handleTime","");
            map.put("hospitalName","");
            if(cmap.get("hospitalName")!=null){
                map.put("hospitalName",cmap.get("hospitalName").toString());
            }
            if(cmap.get("warn_time")!=null){
//                List list = StringUtils.str2List(cmap.get("warn_time").toString()," ",true,true);
//                if(list.size()>1){
//                    map.put("warn_time",list.get(1));
//                }
                map.put("warn_time",cmap.get("warn_time").toString());
            }
            if(cmap.get("push_time")!=null){
//                List list = StringUtils.str2List(cmap.get("push_time").toString()," ",true,true);
//                if(list.size()>0){
//                    map.put("handleTime",list.get(1));
//                }
                map.put("handleTime",cmap.get("push_time").toString());
            }
            if(cmap.get("deviceId")!=null){
                List list = StringUtils.str2List(cmap.get("deviceId").toString(),",",true,true);
                map.put("monitor",list.size());
            }
            if(cmap.get("handle_state")!=null){
                Integer state = Integer.valueOf(cmap.get("handle_state").toString());
                map.put("handle_state",state);
                if(cmap.get("punish_uid")!=null){
                    SysUser punishUid = sysUserMapper.selectUserById(Long.parseLong(cmap.get("punish_uid").toString()));
                    map.put("handlePerson",punishUid.getNickName());
                }
            }

            if(cmap.get("rule_group_id")!=null){
                HisEngineRuleGroup group = hisEngineRuleGroupMapper.selectHisEngineRuleGroupById(Long.parseLong(cmap.get("rule_group_id").toString()));
                map.put("warningName",group.getName());
            }
        }
        return mapList;
    }
    @Override
    public List<HisHosTypeVo> getWarnType() {
        List<HisHosTypeVo> param = new ArrayList<>();
        HisHosTypeVo vo0 = new HisHosTypeVo("医院",0,"医院",1);
        HisHosTypeVo vo1 = new HisHosTypeVo("门诊",1,"门诊",1);
        HisHosTypeVo vo2 = new HisHosTypeVo("诊所",2,"诊所",1);
        HisHosTypeVo vo3 = new HisHosTypeVo("卫生服务中心(站)",3,"卫生服务",1);
        HisHosTypeVo vo4 = new HisHosTypeVo("卫生院(所,室)",4,"卫生院",1);
        HisHosTypeVo vo5 = new HisHosTypeVo("疗养院",5,"疗养院",1);
        HisHosTypeVo vo6 = new HisHosTypeVo("护理中心(站)",6,"护理",1);
        HisHosTypeVo vo7 = new HisHosTypeVo("其它",7,"other",1);
        param.add(vo0);
        param.add(vo1);
        param.add(vo2);
        param.add(vo3);
        param.add(vo4);
        param.add(vo5);
        param.add(vo6);
        param.add(vo7);
        for(HisHosTypeVo vo : param){
            HisHosTypeVo rvo =  getResult(vo);
            vo.setOrgCount(rvo.getOrgCount());
            vo.setPunishOrgCount(rvo.getPunishOrgCount());
            vo.setWarnOrgCount(rvo.getWarnOrgCount());
            vo.setTotalInto(rvo.getTotalInto());
           if(vo.getType()==4){
             vo.setKeys("卫生所");
             HisHosTypeVo rvo1 =  getResult(vo);
             vo.setOrgCount(rvo.getOrgCount()+rvo1.getOrgCount());
             vo.setPunishOrgCount(rvo.getPunishOrgCount()+rvo1.getPunishOrgCount());
             vo.setWarnOrgCount(rvo.getWarnOrgCount()+rvo1.getWarnOrgCount());
             vo.setTotalInto(rvo.getTotalInto()+rvo1.getWarnOrgCount());

             vo.setKeys("卫生室");
             HisHosTypeVo rvo2 =  getResult(vo);
             vo.setOrgCount(rvo.getOrgCount()+rvo2.getOrgCount());
             vo.setPunishOrgCount(rvo.getPunishOrgCount()+rvo2.getPunishOrgCount());
             vo.setWarnOrgCount(rvo.getWarnOrgCount()+rvo2.getWarnOrgCount());
             vo.setTotalInto(rvo.getTotalInto()+rvo2.getWarnOrgCount());
           }
        }
        return param;
    }

    //0当天数据 7 天前  30天前
    @Override
    public List<HisLogVo> getWarnTypeNum(Integer day, List<String> hospitalIds, List<String> signatures) {
        List<HisEngineRuleGroup> list =  hisEngineRuleGroupMapper.selectRuleGroupList();
        List<HisLogVo> mapList = new ArrayList<>();
        for(HisEngineRuleGroup group : list){
            HisLogVo vo = new HisLogVo();
            vo.setName(group.getName());
            vo.setDaykeys(day);
            vo.setGid(group.getId());
            vo.setHospitalIds(hospitalIds);
            vo.setSignatures(signatures);
            //今天
            long hos = warnPreLogMapper.selectHosLogDate(vo);
            long pre = warnPreLogMapper.selectPreLogDate(vo);
            vo.setValue(hos+pre);
            mapList.add(vo);
        }
        return mapList;
    }

    @Override
    public List<HisDataVo> getMiddleMap(List<String> hospitalIds, List<String> signatures) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);

        ReCity city = new ReCity();
        ReArea reArea = new ReArea();
        ReStreet street =new ReStreet();

        List<ReCity> list_city = new ArrayList<>();
        List<ReArea> list_area = new ArrayList<>();
        List<ReStreet> list_street = new ArrayList<>();
        int type = 0;//1 绑定的省 2绑定的市 3绑定的区
        if(StringUtils.isNotEmpty(sysUser.getProvinceCode())){
            type = 1;
            city.setProvinceCode(sysUser.getProvinceCode());
            list_city = reCityMapper.selectReCityList(city);
        }
        if(StringUtils.isNotEmpty(sysUser.getCityCode())){
            type = 2;
            reArea.setCityCode(sysUser.getCityCode());
            list_area = reAreaMapper.selectReAreaList(reArea);
        }
        if(StringUtils.isNotEmpty(sysUser.getAreaCode())){
            type = 3;
            street.setAreaCode(sysUser.getAreaCode());
            list_street = reStreetMapper.selectReStreetList(street);
        }
        List<HisDataVo> hisDataVos=new ArrayList<>();
        OdsHospitalAll odsHospitalAll =new OdsHospitalAll();
        if(type==1){
            for(ReCity local :list_city){
                odsHospitalAll.setCityCode(local.getCode());
                HisDataVo dataVo = makeData(odsHospitalAll,local.getName(),type,local.getCode());
                hisDataVos.add(dataVo);
            }
        }
        if(type==2){
            for(ReArea local :list_area){
                odsHospitalAll.setAreaCode(local.getCode());
                HisDataVo dataVo = makeData(odsHospitalAll,local.getName(),type,local.getCode());
                hisDataVos.add(dataVo);
            }
//            String[] names = {"红花岗区","汇川区","播州区"};
//            for(int i=0;i<3;i++){
//                HisDataVo dataVo = new HisDataVo();
//                dataVo.setCount(3);
//                dataVo.setPercent("15%");
//                dataVo.setName(names[i]);
//                if(i==0){
//                    dataVo.setValue(new String[]{"106.41","27.33"});
//                }
//                if(i==1){
//                    dataVo.setValue(new String[]{"106.92","27.73"});
//                }
//                if(i==2){
//                    dataVo.setValue(new String[]{"106.82",":27.53"});
//                }
//                hisDataVos.add(dataVo);
//            }
        }
        if(type==3){
            for(ReStreet local :list_street){
                odsHospitalAll.setStreetCode(local.getCode());
                HisDataVo dataVo = makeData(odsHospitalAll,local.getName(),type,local.getCode());
                hisDataVos.add(dataVo);
            }
        }
        return hisDataVos;
    }
    public HisDataVo makeData(OdsHospitalAll odsHospitalAll,String name,int type,String code){
        List<HisDataVo> hisDataVos=new ArrayList<>();
        HisDataVo dataVo =new HisDataVo();
        String[] originalArray = new String[2];
        originalArray[0] = "0";
        originalArray[1] = "0";
        List<OdsHospitalAll> odsHospitalAlls = odsHospitalAllMapper.selectOdsHospitalAllList(odsHospitalAll);
        //开始
        if(!CollectionUtils.isEmpty(odsHospitalAlls)){
            dataVo.setName(name);
            int whos =0;
            List<String> list =new ArrayList<>();
            BigDecimal zbTotal= new BigDecimal(0);
            for (OdsHospitalAll od:odsHospitalAlls){
                if(StringUtils.isNotNull(od.getHospitalId())&&StringUtils.isNotNull(od.getSignature())){
                    int size = warnHospitalLogMapper.selectWarnHospitalLogListCount(od.getHospitalId(),od.getSignature());
                    int size1 = warnPreLogMapper.selectWarnPreLogListCount(od.getHospitalId(),od.getSignature());
                    if(size>0||size1>0){
                        whos+=1;
                    }
//                HisArea area =  hisAreaMapper.selectHisArea(odsHospitalAll1.getInstitutionName());
//                if(Objects.nonNull(area)){
//                    originalArray[0] =String.valueOf(area.getLongitude());
//                    originalArray[1] =String.valueOf(area.getLatitude());
//                }
                }
            }

            if(!CollectionUtils.isEmpty(odsHospitalAlls)&&odsHospitalAlls.size()!=0){
                dataVo.setName(name);
                dataVo.setCount(whos);
                int total = odsHospitalAlls.size();
                double result = (double) whos / total;
                result = (double) Math.round(result * 100) / 100;
                String pstr = String.valueOf(result*100)+"%";
                dataVo.setPercent(pstr);
                if(type==1){
                   ReCity city =  reCityMapper.selectReCityByCode(code);
                    if(StringUtils.isNotNull(city)){
                        originalArray[0] =String.valueOf(city.getLo());
                        originalArray[1] =String.valueOf(city.getLa());
                    }

                }else if(type==2){
                   ReArea area =  reAreaMapper.selectReAreaByCode(code);
                   if(StringUtils.isNotNull(area)){
                       originalArray[0] =String.valueOf(area.getLo());
                       originalArray[1] =String.valueOf(area.getLa());
                   }

                }else if(type==3){
                    ReStreet street =  reStreetMapper.selectReStreetByCode(code);
                    if(StringUtils.isNotNull(street)){
                        originalArray[0] =String.valueOf(street.getLo());
                        originalArray[1] =String.valueOf(street.getLa());
                    }

                }
//                dataVo.setPercent(zbTotal.divide(new BigDecimal(odsHospitalAlls.size())).setScale(1,BigDecimal.ROUND_HALF_DOWN).toString()+"%");
            } else {
                dataVo.setPercent("0%");
            }
            dataVo.setValue(originalArray);
        }else {
            List<HisDataVo> dateValue = getDateValue();
            for (HisDataVo dataVo1:dateValue){
                if(name.equals(dataVo1.getName())){
                    dataVo = dataVo1;
                    break;
                }
            }
        }
        //结束
        return dataVo;
    }

    @Override
    public AjaxResult getAdCode(){
        Map map = new HashMap();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        int type = 0;//1 绑定的省 2绑定的市 3绑定的区
        if(StringUtils.isNotEmpty(sysUser.getProvinceCode())){
            type = 1;
            ReProvince p = reProvinceMapper.selectReProvinceByCode(sysUser.getProvinceCode());
            if(StringUtils.isNotNull(p)){
                map.put("adcode",p.getAdcode());
                map.put("name",p.getName());
            }
        }
        if(StringUtils.isNotEmpty(sysUser.getCityCode())){
            type = 2;
            ReCity c = reCityMapper.selectReCityByCode(sysUser.getCityCode());
            if(StringUtils.isNotNull(c)){
                map.put("adcode",c.getAdcode());
                map.put("name",c.getName());
            }
        }
        if(StringUtils.isNotEmpty(sysUser.getAreaCode())){
            type = 3;
            ReArea a = reAreaMapper.selectReAreaByCode(sysUser.getAreaCode());
            if(StringUtils.isNotNull(a)){
                map.put("adcode",a.getAdcode());
                map.put("name",a.getName());
            }
        }
        map.put("level",String.valueOf(type));
        return AjaxResult.success(map);
    }
//    @Override
//    public List<HisDataVo> getMiddleMap(List<String> hospitalIds, List<String> signatures) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Long userId = loginUser.getUserId();
//        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        List<HisDataVo> hisDataVos=new ArrayList<>();
//        if(org.apache.commons.lang3.StringUtils.isNotBlank(sysUser.getAreaCode())){
//            ReStreet street =new ReStreet();
//            street.setAreaCode(sysUser.getAreaCode());
//            List<ReStreet> reStreets = reStreetMapper.selectReStreetList(street);
//            for (ReStreet street1:reStreets){
//                HisDataVo dataVo =new HisDataVo();
//                OdsHospitalAll odsHospitalAll =new OdsHospitalAll();
//                odsHospitalAll.setStreetCode(street1.getCode());
//                String[] originalArray = new String[2];
//                originalArray[0] = "0";
//                originalArray[1] = "0";
//                List<OdsHospitalAll> odsHospitalAlls = odsHospitalAllMapper.selectOdsHospitalAllList(odsHospitalAll);
//                if(!CollectionUtils.isEmpty(odsHospitalAlls)){
//                    dataVo.setName(street1.getName());
//                    int total =0;
//                    int totals =0;
//                    List<String> list =new ArrayList<>();
//                    BigDecimal zbTotal= new BigDecimal(0);
//                    for (OdsHospitalAll odsHospitalAll1:odsHospitalAlls){
//                        int size = warnHospitalLogMapper.selectWarnHospitalLogListCount(odsHospitalAll1.getHospitalId());
//                        totals+=size;
//                        int size1 = warnPreLogMapper.selectWarnPreLogListCount(odsHospitalAll1.getHospitalId());
//                        total+=size1;
//                        zbTotal= new BigDecimal(size).add(new BigDecimal(size1));
//                        HisArea area =  hisAreaMapper.selectHisArea(odsHospitalAll1.getInstitutionName());
//                        if(Objects.nonNull(area)){
//                            originalArray[0] =String.valueOf(area.getLongitude());
//                            originalArray[1] =String.valueOf(area.getLatitude());
//                        }
//                    }
//                    dataVo.setCount(total+totals);
//                    if(!CollectionUtils.isEmpty(odsHospitalAlls)){
//                        dataVo.setPercent(zbTotal.divide(new BigDecimal(odsHospitalAlls.size())).setScale(1,BigDecimal.ROUND_HALF_DOWN).toString()+"%");
//                    } else {
//                        dataVo.setPercent("0");
//                    }
//                    dataVo.setValue(originalArray);
//                } else {
//                    List<HisDataVo> dateValue = getDateValue();
//                    for (HisDataVo dataVo1:dateValue){
//                        if(street1.getName().equals(dataVo1.getName())){
//                            dataVo = dataVo1;
//                            break;
//                        }
//                    }
//                }
//                hisDataVos.add(dataVo);
//            }
//        }
//        return hisDataVos;
//    }

    private List<HisDataVo> getDateValue() {
        List<HisDataVo> hisDataVos =new ArrayList<>();
        HisDataVo dataVo =new HisDataVo();
        dataVo.setName("高桥镇");
        dataVo.setCount((int) 0);
        dataVo.setPercent("0%");
        dataVo.setValue(new String[]{"106.895979","27.725261"});
        hisDataVos.add(dataVo);
        HisDataVo dataVo1 =new HisDataVo();
        dataVo1.setName("董公寺镇");
        dataVo1.setCount((int) 0);
        dataVo1.setPercent("0%");
        dataVo1.setValue(new String[]{"106.94555","27.760774"});
        hisDataVos.add(dataVo1);
        HisDataVo dataVo2 =new HisDataVo();
        dataVo2.setName("高坪镇");
        dataVo2.setCount((int) 0);
        dataVo2.setPercent("0%");
        dataVo2.setValue(new String[]{"106.92496","27.82977"});
        hisDataVos.add(dataVo2);
        HisDataVo dataVo3 =new HisDataVo();
        dataVo3.setName("团泽镇");
        dataVo3.setCount((int) 0);
        dataVo3.setPercent("0%");
        dataVo3.setValue(new String[]{"107.087998","27.799944"});
        hisDataVos.add(dataVo3);
        HisDataVo dataVo4 =new HisDataVo();
        dataVo4.setName("板桥镇");
        dataVo4.setCount((int) 0);
        dataVo4.setPercent("0%");
        dataVo4.setValue(new String[]{"106.909975","28.00029"});
        hisDataVos.add(dataVo4);
        HisDataVo dataVo5 =new HisDataVo();
        dataVo5.setName("泗渡镇");
        dataVo5.setCount((int) 0);
        dataVo5.setPercent("0%");
        dataVo5.setValue(new String[]{"106.947112","27.925694"});
        hisDataVos.add(dataVo5);
        HisDataVo dataVo6 =new HisDataVo();
        dataVo6.setName("沙湾镇");
        dataVo6.setCount((int) 0);
        dataVo6.setPercent("0%");
        dataVo6.setValue(new String[]{"106.816772","27.895999"});
        hisDataVos.add(dataVo6);
        HisDataVo dataVo7 =new HisDataVo();
        dataVo7.setName("山盆镇");
        dataVo7.setCount((int) 0);
        dataVo7.setPercent("0%");
        dataVo7.setValue(new String[]{"106.66546","27.950423"});
        hisDataVos.add(dataVo7);
        HisDataVo dataVo8 =new HisDataVo();
        dataVo8.setName("芝麻镇");
        dataVo8.setCount((int) 0);
        dataVo8.setPercent("0%");
        dataVo8.setValue(new String[]{"106.617726","27.865139"});
        hisDataVos.add(dataVo8);
        HisDataVo dataVo9 =new HisDataVo();
        dataVo9.setName("松林镇");
        dataVo9.setCount((int) 0);
        dataVo9.setPercent("0%");
        dataVo9.setValue(new String[]{"106.647826","27.735407"});
        hisDataVos.add(dataVo9);
        HisDataVo dataVo10 =new HisDataVo();
        dataVo10.setName("毛石镇");
        dataVo10.setCount((int) 0);
        dataVo10.setPercent("0%");
        dataVo10.setValue(new String[]{"106.694301","27.809974"});
        hisDataVos.add(dataVo10);
        return hisDataVos;
    }



    public HisHosTypeVo getResult(HisHosTypeVo vo){
        vo.setOrgCount(0);
        vo.setInOrgCount(0);
        vo.setPunishOrgCount(0);
        vo.setWarnOrgCount(0);
        vo.setTotalInto(0);
        vo.setDeviceCount(0);
        //接入机构数
        Integer into =  engineWarnTypeMapper.selectHosTypeCount(vo);
        //处罚数
        Integer punish = engineWarnTypeMapper.selectHosTypePunishCount(vo);
        if(into!=null){
           vo.setInOrgCount(into);
        }
        if(punish!=null){
            vo.setPunishOrgCount(punish);
        }
        //预警数
        List<HisHosTypeVo> hoswarn = engineWarnTypeMapper.selectHosTypeWarns(vo);
        List<HisHosTypeVo> prewarn = engineWarnTypeMapper.selectHosTypeWarns(vo);
        Set<String> set = new HashSet<>();
        for(HisHosTypeVo v1 : hoswarn){
            set.add(v1.getRegisterNumber());
        }
        for(HisHosTypeVo v2 : prewarn){
            set.add(v2.getRegisterNumber());
        }
        //机构数
        vo.setWarnOrgCount(set.size());
        //按种类所有机构数
        vo.setIsInto(null);
        Integer totaltype =  engineWarnTypeMapper.selectHosTypeCount(vo);
        if(totaltype!=null){
            vo.setOrgCount(totaltype);
        }
        //不按种类分所有接入机构数
        vo.setIsInto(1);
        vo.setKeys(null);
        Integer total =  engineWarnTypeMapper.selectHosTypeCount(vo);
        if(total!=null){
            vo.setTotalInto(total);
        }
        return vo;
    }

}

